<template>
  <div>
    <a-select
      ref="select"
      :disabled="disabled"
      :mode="multiple ? 'multiple' : ''"
      :max-tag-count="maxTagCount"
      :allowClear="allowClear"
      v-model:value="state.value"
      @change="handleChange"
      :placeholder="placeholder"
      style="width: 100%"
    >
      <a-select-option
        v-for="item in state.options"
        :key="item[id]"
        :value="item[id]"
        >{{ item[label] }}</a-select-option
      >
    </a-select>
  </div>
</template>
<script setup>
import { reactive, watch } from "vue";
/**
 * props
 */
const props = defineProps({
  value: {
    type: [String, Array, Number, Boolean],
    default: "",
  },
  options: {
    type: [Array, Object],
    default: () => [],
  },
  id: {
    type: String,
    default: "value",
  },
  label: {
    type: String,
    default: "label",
  },
  multiple: Boolean,
  search: {
    type: Boolean,
    defualt: true,
  },
  keys: {
    type: String,
    defualt: "",
  },
  placeholder: {
    type: String,
    default: "请选择",
  },
  maxTagCount: {
    type: Number,
    defualt: 100,
  },
});
/**
 * emit
 */
const emit = defineEmits(["update:value", "change"]);
/**
 * state
 */
const state = reactive({
  value: props.multiple ? [] : undefined,
  options: [],
});
const handleChange = (value, option) => {
  emit("update:value", value);
  emit("change", value);
};
/**
 * clear
 */
const clear = () => {
  state.value = "";
};
watch(
  () => props.value,
  (val) => {
    state.value = val || undefined;
  },
  { immediate: true }
);
watch(
  () => props.options,
  (val) => {
    state.options = val || [];
  },
  { immediate: true }
);
defineExpose({ clear });
</script>
<style lang="scss" scoped></style>
